import 'package:flutter/material.dart';
import '../services/ScreenAdapter.dart';

// 本地存储
import '../services/SearchServices.dart';

class SearchPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => SearchPageState();
}

class SearchPageState extends State {
  List _hotSearchData = ['超级秒杀', '办公电脑', '儿童小汽车', '唇彩唇蜜'];
  List _historyData = [];
  var keyWords;

  @override
  void initState(){
    super.initState();

    // 从本地获取历史数据
    _getHistoryData();
  }

  @override
  Widget build(BuildContext context) {
    ScreenAdapter.init(context);
    return Scaffold(
      appBar: AppBar(
        title: Container(
          alignment: Alignment.center,
          height: ScreenAdapter.height(68),
          padding: EdgeInsets.all(10),
          decoration: BoxDecoration(
            color: Colors.black12,
            borderRadius: BorderRadius.circular(34),
          ),
          child: TextField(
              style: TextStyle(fontSize: ScreenAdapter.size(34)),
              autofocus: true,
              decoration: InputDecoration(
                  border: OutlineInputBorder(
                      borderSide: BorderSide.none,
                      borderRadius: BorderRadius.circular(34)
                  )
              ),
              onChanged: (value){
                this.setState(() {
                  keyWords = value;
                });
              }
          ),
        ),
        actions: [
          Container(
            alignment: Alignment.center,
            height: ScreenAdapter.height(68),
            margin: EdgeInsets.only(right: 10),
            child: InkWell(
              child: Text('搜索',style:TextStyle(fontSize: ScreenAdapter.size(34))),
              onTap: (){
                // 将搜索数据保存到本地中
                SearchServices.setHistoryData(this.keyWords);

                // 跳转到productList页面
                Navigator.pushReplacementNamed(context,'/productList',arguments: {
                  "keyWords": this.keyWords
                });
              },
            ),
          )
        ],
      ),
      body: Container(
        margin: EdgeInsets.all(10),
        child: ListView(
          children: [

            // 热搜
            Container(
              child: Text('热搜',style: Theme.of(context).textTheme.title),
            ),
            Divider(),
            Wrap(
              children: _hotSearchList(),
            ),
            Divider(thickness:10,height:30,color: Color.fromRGBO(200, 200, 200, 0.2)),

            // 历史搜索
            Container(
              child: Text('历史搜索',style: Theme.of(context).textTheme.title),
            ),
            Divider(),
            ListView.builder(
              shrinkWrap: true,
              itemCount: _historyData.length,
              itemBuilder: (context, index){
                return InkWell(
                  child: Container(
                    alignment: Alignment.centerLeft,
                    height: ScreenAdapter.height(80),
                    decoration: BoxDecoration(
                      border: Border(
                        bottom: BorderSide(
                          color: Color.fromRGBO(200, 200, 200, 0.3)
                        )
                      )
                    ),
                    child: Text('${_historyData[index]}',style:TextStyle(color: Colors.black54)),
                  ),
                  onTap: (){
                    Navigator.pushReplacementNamed(context,'/productList',arguments: {
                      "keyWords": this._historyData[index]
                    });
                  },
                  onLongPress: (){
                    _showDialog(this._historyData[index]);
                  }
                );
              },
            ),

            // 清空历史搜索
            SizedBox(height: ScreenAdapter.height(100)),
            InkWell(
              child: Container(
                padding: EdgeInsets.all(10),
                margin: EdgeInsets.only(left: 50,right:50),
                decoration: BoxDecoration(
                    border: Border.all(
                      color: Colors.black38,
                    )
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(Icons.delete_outline,color:Colors.black38),
                    Container(
                      child: Text('清空历史搜索',style:TextStyle(color: Colors.black54)),
                    )
                  ],
                ),
              ),
              onTap: () async {
                await SearchServices.cleanHistoryData();
                // 重新从本地获取数据
                _getHistoryData();
              },
            )

          ],
        ),
      )
    );
  }

  // 删除长按的历史搜索记录
  _showDialog(keyWords){
    return showDialog(
        barrierDismissible: false,   //点击灰色背景时弹框是否消失
        context: context,
        builder: (context){
          return AlertDialog(
            title: Text('提示信息！'),
            content: Text('您确定要删除吗？'),
            actions: [
              FlatButton(
                child: Text('取消'),
                onPressed: (){
                  Navigator.pop(context,'Cancle');
                },
              ),

              FlatButton(
                child: Text('确定'),
                onPressed: () async {
                  // 删除长按历史搜索数据
                  await SearchServices.removeHistoryItem(keyWords);

                  // 重新从本地获取历史数据
                  _getHistoryData();

                  Navigator.pop(context,'Ok');
                },
              ),
            ],
          );
        }
    );
  }

  //  热搜组件列表
  _hotSearchList() {
    return _hotSearchData.map((value){
      return Container(
        margin: EdgeInsets.all(5),
        padding: EdgeInsets.all(10),
        child: Text('$value',style: TextStyle(fontSize: ScreenAdapter.size(30),)),
        decoration: BoxDecoration(
          color: Color.fromRGBO(200, 200, 200, 0.3),
          borderRadius: BorderRadius.circular(30),
        ),
      );
    }).toList();
  }

  // 从本地获取历史数据
  _getHistoryData() async {
    List res = await SearchServices.getHistoryData();
    this.setState(() {
      _historyData = res;
    });
  }
}
